cd "${utils}"

forvalues y = 2005/2020 {
	local suff
	if `y' <= 2015 {
		local suff _complet
	}
	
	file open myfile using "${utils}\extract_perim.sas", write replace
	// Edit path to store resulting source datafile
	file write myfile `"libname perim "${rawsource}\DECFISCPRO_PERIM_`y'";"' _n
	file write myfile `"proc export data = perim.perim_exer_`y'`suff'"' _n
	file write myfile `"outfile = '${tmp}\mere_fille_fisc_`y''"' _n
	file write myfile `"dbms = dta replace ; run; "'_n
	file close myfile

	shell "${SASPath}" "${utils}\extract_perim.sas"
	}
	
**NB: assume groupes fiscaux do not change between 2004 and 2005	
use "${tmp}\mere_fille_fisc_2005", clear
save "${tmp}\mere_fille_fisc_2004", replace
	
tempfile main
forvalues y = 2004/2020 {
	cd $intpath
	global y `y'
	use "${tmp}\mere_fille_fisc_${y}.dta", clear
	gen year = $y
	ren *, lower	
	rename sirengm siren
	rename sirengt siren_gf
	drop if mi(siren_gf)
	cap append using `main'
	save `main', replace
	}
sort siren year
destring siren, replace force
drop if mi(siren)
destring siren_gf, replace force
drop if mi(siren_gf)
gen siren2 = siren_gf
ren siren siren1
gen n = _n
reshape long siren, i(n) j(rk)
drop if siren == 0
drop n rk
gduplicates drop
gduplicates tag siren year, gen(dup)
gen same = siren_gf == siren
bys siren year (same): drop if dup != 0 & _n != _N
drop same dup
save "${data}/Utils/Mere_fille_0420", replace
